package com.purchase.manage.untils;

import com.purchase.manage.damian.OrderQuotation;
import com.purchase.manage.damian.OrderQuotationProduct;
import com.purchase.manage.damian.OrderQuotations;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetExcel {
    public static OrderQuotations getOrderQuotations(MultipartFile rfile) throws IOException, ParseException {
        OrderQuotation odeQuotation=new OrderQuotation();
        odeQuotation.setQuotationOrderNumber( UUID.randomUUID().toString());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
        // 生成随机的文件名
        // String filename = UUID.randomUUID().toString() + ".jpg";
        List<OrderQuotationProduct> listOrder=new ArrayList<OrderQuotationProduct>();
        //获取源文件名字
        String originalFilename = rfile.getOriginalFilename();
        //获取源文件后缀
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置为临时文件
        File tempFile = File.createTempFile("temp", fileSuffix);
        rfile.transferTo(tempFile);
        FileInputStream file = new FileInputStream(tempFile);
        int count=0;

        //创建迭代器
        Iterator<Row> rowIterator = null;
        //根据excel文件后缀获取信息
        if (originalFilename.endsWith(".xls")) {
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            HSSFSheet sheet = workbook.getSheetAt(0);
            rowIterator= sheet.iterator();
        } else if(originalFilename.endsWith(".xlsx")) {
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            rowIterator = sheet.iterator();
        }


        // 从第二行开始读取数据，跳过表头
        rowIterator.next();
        while (rowIterator.hasNext()) {
            count=0;
            //下一行
            Row row = rowIterator.next();
            int lastCellNum = row.getLastCellNum();
            //最大数值
            int numericValue=0;
            String name="";
//            if (row.getCell(count).getCellType() == CellType.NUMERIC) {
//                numericValue = (int)row.getCell(count).getNumericCellValue();
//                // 处理数字类型的值
//            } else if (row.getCell(count).getCellType() == CellType.STRING) {
//                name = row.getCell(count).getStringCellValue();
//                // 处理字符串类型的值
//            }

            //根据name获取相应的值

            if(name.equals("报价单位名称")){
                count=incre(count,row,lastCellNum,name);
                odeQuotation.setVenderName(row.getCell(count).getStringCellValue());
                continue;
            }



            if(name.equals("联系人")){
                count=incre(count,row,lastCellNum,name);
                odeQuotation.setVenderLinker(row.getCell(count).getStringCellValue());
                count=incre(count,row,lastCellNum,name);
                //给联系人赋值
                name = row.getCell(count).getStringCellValue();
                if(name.equals("联系电话")){
                    count=incre(count,row,lastCellNum,name);

                    odeQuotation.setVenderPhone((int)row.getCell(count).getNumericCellValue());
                    count=incre(count,row,lastCellNum,name);

                }

                //给邮箱赋值
                name = row.getCell(count).getStringCellValue();
                if(name.equals("邮箱")){
                    count=incre(count,row,lastCellNum,name);
                    odeQuotation.setVenderEmail(row.getCell(count).getStringCellValue());
                    continue;
                }
            }


            if(name.equals("联系地址")){
                count=incre(count,row,lastCellNum,name);
                odeQuotation.setVenderAddress(row.getCell(count).getStringCellValue());
            }

            if(numericValue>=1){
                OrderQuotationProduct q=new OrderQuotationProduct();
                for(int i=0;i<9;i++){
                    count=incre(count,row,lastCellNum,name);
                    if(i==0){
                        q.setProductName(row.getCell(count).getStringCellValue());
                    }else if(i==1){
                        q.setProductSpecifications(row.getCell(count).getStringCellValue());
                    }else if(i==2){
                        q.setProductTechnicalParameters(row.getCell(count).getStringCellValue());
                    }else if(i==3){
                        q.setProductBrand(row.getCell(count).getStringCellValue());
                    }else if(i==4){
                        q.setProductUnit(row.getCell(count).getStringCellValue());
                    }else if(i==5){
                        q.setProductNumber((int)row.getCell(count).getNumericCellValue());
                    }else if(i==6){
                        q.setProductUnitPrice(new BigDecimal(row.getCell(count).getNumericCellValue()));
                    }else if(i==7){
                        q.setProductMoney(new BigDecimal(row.getCell(count).getNumericCellValue()));
                    }
                    else if(i==8){
                        q.setProductRemark(row.getCell(count).getStringCellValue());
                    }
                }
                q.setQuotationId(odeQuotation.getQuotationOrderNumber());
                listOrder.add(q);

            }

            if(name.equals("含运费、安装调试、税等总价（元）：")){
                odeQuotation.setPriceIncludingTax(new BigDecimal(row.getCell(6).getNumericCellValue()));
                continue;
            }

            if(name.contains("交货时间")){
                Matcher matcher = pattern.matcher(name);
                if (matcher.find()) {
                    odeQuotation.setDeliveryTime(formatter.parse(matcher.group()));
                }

            }
            if(name.contains("质保期")){
                Matcher matcher = pattern.matcher(name);
                if (matcher.find()) {
                    odeQuotation.setWarranty(formatter.parse(matcher.group()));
                }
                count=incre(count,row,lastCellNum,name);
                name=row.getCell(count).getStringCellValue();
                matcher = pattern.matcher(name);
                if (matcher.find()) {
                    odeQuotation.setQuotationDate(formatter.parse(matcher.group()));
                }
                continue;
            }

            if(name.contains("备注")){
                odeQuotation.setRemark(name);
            }
        }
        file.close();
        //创建返回对象，将解析出的对象赋值
        OrderQuotations orderQuotations=new OrderQuotations();
        orderQuotations.setOrderQuotation(odeQuotation);
        orderQuotations.setOrderQuotationProduct(listOrder);

        return orderQuotations;
    }
    //用于判断数据是否为空
    public static int incre(int count,Row row,int lastCellNum,String name){
        count++;
//        while (row.getCell(count).getCellType() == CellType.BLANK){
//            count+=1;
//            if(count>=lastCellNum){
//                throw new SecurityException(name+"为空");
//            }
//        }
        return count;
    }

}
